package com.tool4j.util;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.web.server.ServerWebExchange;

/**
 * 用户权限信息 - WebFlux 兼容版本
 *
 * @author Deng.Weiping
 * @since 2023/10/31 8:51
 */
public class UserPermission {

    /**
     * 在 ServerWebExchange 中存储用户信息的 key
     */
    public static final String ATTRIBUTE_KEY = "user_permission_info";

    /**
     * 从 ServerWebExchange 中获取用户信息（推荐方式）
     */
    public static UserInfo get(ServerWebExchange exchange) {
        return exchange.getAttribute(ATTRIBUTE_KEY);
    }

    /**
     * 将用户信息存入 ServerWebExchange（推荐方式）
     */
    public static void set(ServerWebExchange exchange, UserInfo data) {
        exchange.getAttributes().put(ATTRIBUTE_KEY, data);
    }

    /**
     * 清除用户信息（可选）
     */
    public static void remove(ServerWebExchange exchange) {
        exchange.getAttributes().remove(ATTRIBUTE_KEY);
    }

    /**
     * 判断是否登录
     */
    public static Boolean isLogin(ServerWebExchange exchange) {
        UserInfo user = null;
        if (exchange != null) {
            user = get(exchange);
        }
        return user != null && user.getUserId() != null;
    }

    @Data
    @Accessors(chain = true)
    public static class UserInfo {
        private Long userId;
        private String token;
        private String username;
        private String ip;
        private String region;
        private String phoneNum;
        private String email;
        private String role;
    }
}